import * as express from 'express';
import * as swagger from 'swagger-express-middleware';
import { interfaces, controller, httpGet, httpPost, queryParam } from 'inversify-express-utils';
import { Container, inject } from 'inversify';
import { UserInfo, IUserService, tsIUserService } from '../service/api/user';
import { hredis } from 'src/app';
import { llog } from 'src/util/logger';
import { Config } from './../app';

export default function rootControllerFactory(container: Container) {
	@controller('/')
	class RootController implements interfaces.Controller {
		@inject(tsIUserService) userService: IUserService;

		@httpGet('getIP')
		public list(request: express.Request, response: express.Response, next: express.NextFunction): string {
			let ip = request.header('x-forwarded-for') || request.connection.remoteAddress;
			return ip;
		}

		@httpPost('check')
		public async check(request: express.Request, response: express.Response, next: express.NextFunction): Promise<string> {
			let info = {
				pkgs: {
					iOS: {
						limit: '1.13',
						url: 'http://www.baidu.com',
					},
					Android: {
						limit: '1.24',
						url: 'http://www.baidu.com',
					},
				},
				servers: [[], [], [], [], []],
			};

			// 从用户身上获取专有服务器
			let id = request.body.id;
			let userInfo = await this.userService.Get(id);
			if (userInfo != null) {
				// let userServers = JSON.parse(userInfo.serversInfo);
				info.servers.forEach((v, k) => {
					// v.concat(userServers[k]);
				});
			}

			// 从配置中获取固定服务器
			let updateServers = Config.getUpdateServer();
			if (updateServers) info.servers[0] = info.servers[0].concat(updateServers);

			return JSON.stringify(info);
		}

		@httpGet('config')
		public async getconfig(request: express.Request, response: express.Response, next: express.NextFunction) {
			let config = {
				adImages: JSON.parse(await hredis.get('config:adImage')),
			};
			// llog('getconfig', config);
			response.json(config);
		}
	}
	return RootController;
}
